﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Mail;
using System.Net;
using System.Xml.Linq;

namespace MailSender
{
    public partial class SenderForm : Form
    {
        public SenderForm()
        {
            InitializeComponent();
        }

        private void SendMailBt_Click(object sender, EventArgs e)
        {
          

            string toAddress = ReceiveTxt.Text;
            //string fromAddress = SenderTxt.Text;
            MailAddress fromAddress = new MailAddress(SenderTxt.Text);
            string[] tos= toAddress.Split(new Char[] { ';' });
            MailMessage message = this.htmlEditor1.XMailMessage;
            if (tos.Length>0)
            {
                foreach (var item in tos)
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        message.To.Add(item);
                    }
                    
                }
            }  
            // string htmlBodyContent = "如果你的看到<b>这个</b>， 说明你是在以 <span style=\"color:red\">HTML</span> 格式查看邮件<br><br>";   
            // htmlBodyContent += "<a href=\"http://www.fenbi360.net粉笔编程网</a> <img src=\"cid:weblogo\">";
            //AlternateView htmlBody = AlternateView.CreateAlternateViewFromString(htmlBodyContent, null, "text/html");
            
            // LinkedResource lrImage = new LinkedResource(@"c:\\D4100.jpg", "image/gif");   
            //lrImage.ContentId = "weblogo"; //此处的ContentId 对应 htmlBodyContent 内容中的 cid: ，如果设置不正确，请不会显示图片   
            //htmlBody.LinkedResources.Add(lrImage);   
  
            //message.AlternateViews.Add(htmlBody);  

            message.From = fromAddress;
            string subject = SubjectTxt.Text;
            //string body = MailContentTxt.Text;
            message.Headers.Add("Disposition-Notification-To", fromAddress.Address);
            message.Headers.Add("X-Website", "http://www.xinglongjian.com");
            message.Headers.Add("ReturnReceipt", "1");
            message.ReplyToList.Add(fromAddress);

            message.Subject = subject;
            
            //message.IsBodyHtml = true;
           // message.BodyEncoding = Encoding.UTF8;

            ////如果发送失败，SMTP 服务器将发送 失败邮件告诉我   
            message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; 

            bool isssl = IsSSLCheckbox.Enabled;
            XDocument doc = XDocument.Load(SysConstants.DefaultHostFile);
            XElement config = doc.Element("config");

            string defaultHost = config.Element("host").Value;
            int defaultPort = int.Parse(config.Element("port").Value);


            SmtpClient client = new SmtpClient(defaultHost, defaultPort);
            client.Credentials = new NetworkCredential(config.Element("username").Value, config.Element("password").Value);
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.EnableSsl = isssl;
            ////异步发送完成时的处理事件   
            client.SendCompleted += new SendCompletedEventHandler(smtp_SendCompleted);
            ////异步发送
            client.SendAsync(message,null);
            //MessageBox.Show("发送成功！！");
        }

        void smtp_SendCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                MessageBox.Show("发送被取消");
            }
            else
            {
                if (e.Error == null)
                {
                    MessageBox.Show("发送成功");
                }
                else
                {
                    MessageBox.Show("发送失败： " + e.Error.Message);
                }
            }
        }   

        private void MailConfigToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DefaultFrom defaultfrom = new DefaultFrom();
            defaultfrom.ShowDialog();
        }

        private void FromAddCheckBox_Click(object sender, EventArgs e)
        {
            if (FromAddCheckBox.Checked == true)
            {
                //FromAddCheckBox.Checked = true;
                SenderTxt.ReadOnly = true;
                XDocument doc = XDocument.Load(SysConstants.DefaultHostFile);
                XElement config = doc.Element("config");
                SenderTxt.Text = config.Element("from").Value;
            }
            else
            {
                //FromAddCheckBox.Checked = false;
                SenderTxt.ReadOnly = false;
                SenderTxt.Text = string.Empty;
            }
        }

        private void ServerConfigToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ServerManage sManage = new ServerManage();
            sManage.ShowDialog();
        }

        private void AddReceiveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ToAddressManage toAddress = new ToAddressManage();
            toAddress.ShowDialog();
        }

        private void SelectToBt_Click(object sender, EventArgs e)
        {

        }

        private void AllAddressCheckBox_Click(object sender, EventArgs e)
        {
            if (AllAddressCheckBox.Checked == true)
            {
                //FromAddCheckBox.Checked = true;
                ReceiveTxt.ReadOnly = true;
                XDocument doc = XDocument.Load(SysConstants.ToAddressFile);
                XElement config = doc.Element("config");
                List<XElement> allTos= config.Elements("toadd").ToList();
                if (allTos.Count>0)
                {
                    StringBuilder sbuf = new StringBuilder();
                    foreach (var item in allTos)
	                {
                        sbuf.Append(item.Attribute("email").Value).Append(";");
	                }
                    ReceiveTxt.Text = sbuf.ToString();
                }
            }
            else
            {
                //FromAddCheckBox.Checked = false;
                ReceiveTxt.ReadOnly = false;
                ReceiveTxt.Text = string.Empty;
            }
        }
    }
}
